import os
import re


def main(tpl_file, dst_file):
    cFileList = []
    hPathList = []
    sFileList = []
    ldFileList = []

    dList = ["."]

    cmsis_dir = ''
    periph_dir = ''
    with open(tpl_file, "r") as f:
        for line in f.readlines():
            searchObj = re.search(
                r'^\s*(GD32_CMSIS_LIBRARY_DIR.*)\s*=\s*([^\s]+)$', line)
            if searchObj:
                cmsis_dir = searchObj.group(2)
                print("GD32F4xx CMSIS: %s" % cmsis_dir)
                hPathList.append(cmsis_dir)

            searchObj = re.search(
                r'^\s*(GD32_SP_LIBRARY_DIR.*)\s*=\s*([^\s]+)$', line)
            if searchObj:
                periph_dir = searchObj.group(2)
                print("GD32F4xx_standard_peripheral: %s" % periph_dir)
                if os.path.relpath(periph_dir).startswith('..'):
                    dList.insert(0, periph_dir)

    for d in dList:
        for root, _, files in os.walk(d):
            if os.path.relpath(root) == os.path.relpath(cmsis_dir):
                continue
            if os.path.relpath(root) == os.path.relpath(periph_dir):
                continue
            for file in files:
                # .decode('gbk').encode('utf-8')
                file_path = os.path.join(root, file)
                file_path = os.path.relpath(file_path).replace('\\', '/')
                if file.endswith(".c"):
                    cFileList.append(file_path)
                if file.endswith(".h"):
                    hPath = os.path.dirname(file_path)
                    if hPathList.count(hPath) == 0 and os.path.exists(hPath):
                        hPathList.append(hPath)
                if file.endswith(".s"):
                    if '/ARM/' not in file_path and '/IAR/' not in file_path:
                        sFileList.append(file_path)
                if file.endswith(".ld"):
                    ldFile = file_path
                    ldFileList.append(ldFile)
    cFileList.sort()
    hPathList.sort()
    hPathList.append('.')
    print("C sources:\n\t", '\n\t'.join(cFileList))
    print("header dirs:\n\t", '\n\t'.join(hPathList))
    print("asm files:\n\t", '\n\t'.join(sFileList))
    print("ld files:\n\t", '\n\t'.join(ldFileList))

    cFileStr = "C_SOURCES += "
    hPathStr = "C_INCLUDES += "
    sFileStr = "ASM_SOURCES += "
    ldFileStr = "LDSCRIPT += "
    for listStr in cFileList:
        cFileStr += " \\\n" + listStr
        # cFileStr += "C_SOURCES += " + listStr + "\n"
    for listStr in hPathList:
        hPathStr += " \\\n-I" + listStr
        # hPathStr += "C_INCLUDES += -I" + listStr + "\n"
    for listStr in sFileList:
        sFileStr += " \\\n" + listStr
        # sFileStr += "ASM_SOURCES += " + listStr + "\n"
    for listStr in ldFileList:
        ldFileStr += " \\\n" + listStr
        # ldFileStr += "LDSCRIPT += " + listStr + "\n"

    cFileStr = cFileStr.replace(periph_dir, '$(GD32_SP_LIBRARY_DIR)')

    fileStr = ''
    with open(tpl_file, "r") as f:
        fileStr = f.read()
    fileStr = fileStr.replace("@@C_SOURCES@@", cFileStr)
    fileStr = fileStr.replace("@@C_INCLUDES@@", hPathStr)
    fileStr = fileStr.replace("@@ASM_SOURCES@@", sFileStr)
    fileStr = fileStr.replace("@@LDSCRIPT@@", ldFileStr)

    with open(dst_file, "w") as f:
        f.write(fileStr)


if __name__ == '__main__':
    main("./support_files/Makefile.template", "./Makefile")
